package com.xxy.partnermatch.job;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xxy.partnermatch.model.entity.User;
import com.xxy.partnermatch.service.UserService;
import jakarta.annotation.Resource;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * ClassName: PreCacheJob
 * Package: com.xxy.partnermatch.job
 * Description: 定时任务
 *
 * @Author 十一
 * @Create 2024/11/18 22:08
 * @Version 1.0
 */
@Component
@Slf4j
public class PreCacheJob {

    // 重点用户 (第一个用户访问还是很慢)
    private final List<Long> mainUserList = List.of(1L);

    @Resource
    private UserService userService;

    @Resource
    private RedisTemplate redisTemplate;

    @Resource
    private RedissonClient redissonClient;

    // 每天执行, 预热推荐用户
//    @Scheduled(cron = "0 12 1 * * *")   // 自己设置时间测试
    public void doCacheRecommendUser() {
        // 获取锁
        RLock lock = redissonClient.getLock("xuxuanya:precachejob:docache:lock");
        try {
            // 只有一个线程可以抢到锁
            if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                System.out.println("getLock: " + Thread.currentThread().getName());
                for (Long userId : mainUserList) {
                    // 1. 查询数据库
                    QueryWrapper<User> queryWrapper = new QueryWrapper<>();
                    Page<User> userPage = userService.page(new Page<>(1, 20), queryWrapper);
                    String redisKey = String.format("xuxuanya:user:recommend: %s", mainUserList);
                    ValueOperations valueOperations = redisTemplate.opsForValue();
                    // 2. 写缓存, 并设置 30s 过期
                    try {
                        valueOperations.set(redisKey, userPage, 30000, TimeUnit.MILLISECONDS);
                    } catch (Exception e) {
                        log.error("redis set key error: ", e);
                    }
                }
            }
        } catch (Exception e) {
            log.error("doCacheRecommendUser error", e);
        } finally {
            // 只能释放自己的锁
            if (lock.isHeldByCurrentThread()) {
                System.out.println("unlock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }

}
